
export class HttpMgr {
    private static instance: HttpMgr;
    private _xhr: any;
    private constructor() {
    }
    public static getInstance(): HttpMgr {
        if (this.instance == null) {
            this.instance = new HttpMgr();
        }
        return this.instance;
    }
    
    httpGet(url: string, params: object = {}, callback: Function) {
        let dataStr = '';
        Object.keys(params).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
        if(!window['wx']){
            fetch(url,{mode: 'cors'})
            .then(response => response.json())
            .then(data => {
                console.log("收到服务器数据:",data)
                callback(true, data);
            })
            .catch(error => {
                callback(false, error);
            });
            return  
        }
        let xhr = this._xhr??new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.open("GET", url, true);
        // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                let response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let httpStatus = xhr.statusText;
                    callback(true, JSON.parse(response));
                } else {
                    callback(false, response);
                }
            } else {
            }
        };
        xhr.ontimeout = function () {
            // 请求超时时调用回调函数
            callback(false, "请求超时");
        };
        xhr.onerror = function () {
            // 请求出错时调用回调函数
            callback(false, "请求出错");
        };
        xhr.send();
    }

    httpPost(url?: string,oparams: object = null, callback?: Function) {
          
        let xhr = new XMLHttpRequest()
        let datastr = null;
        if (oparams) {
            datastr = ''
            Object.keys(oparams).forEach(key => {
                datastr += key + '=' + oparams[key]+ '&';
            })
            if (datastr !== '') {
                datastr = datastr.substr(0, datastr.lastIndexOf('&'));
            }
        }
        xhr.timeout = 2000; // 
        let httpUrl = url
        xhr.open("POST", httpUrl,true);
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
        // xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    let response = xhr.responseText;
                    if (HttpMgr.isPass(response)) {
                        if (callback) {
                            callback(response);
                        }
                    }
                } else {
                    if (callback) {
                        callback()
                    }
                }
            }
        }
        xhr.ontimeout = function () {
            if (callback) {
                callback()
            }
        }
        xhr.onerror = function () {
            if (callback) {
                callback()
            }
        }
        console.log("httpPost", httpUrl, datastr)
        if (datastr) {
            xhr.send(datastr);
        } else {
            xhr.send();
        }
    }
    private static isPass(json: string): boolean {
        return true;
    }
    openid: string = "wxe80f4334784a03af";
    saveUserData(uid:string,userData:object) {
        HttpMgr.getInstance().httpPost("https://game.gztywlkj.cn/user/saveUserData",{ uid:uid+"",openid:this.openid,userdata:JSON.stringify(userData)},(res)=>{
            console.log("saveUserData",res)
        })
    }
    getUserData(uid:string,callback:Function,failCallback?:Function) {
        HttpMgr.getInstance().httpGet("https://game.gztywlkj.cn/user/getUserData",{uid:uid+"",openid:this.openid},function(isSucc:boolean,data){
            if(isSucc){
                if (data.code === -1) {
                    callback(false)
                } else {
                    callback(true,data.data)
                }
            }else{
                failCallback&&failCallback()
            }
        })
    }
}